<template>
  <view class="public-container">
    <view class="header">
      <text class="title">发布动态</text>
    </view>

    <view class="content-box">
      <!-- 文本内容区域 -->
      <view class="text-area">
        <textarea
          class="content-textarea"
          v-model="contentText"
          placeholder="分享你的想法..."
          maxlength="500"
          auto-height
        />
        <text class="text-counter">{{ contentText.length }}/500</text>
      </view>

      <!-- 照片上传区域 -->
      <view class="media-upload-area" v-if="publishType === 'photo' && showMediaSelector">
        <view class="photo-grid">
          <!-- 已上传照片预览 -->
          <view class="photo-item" v-for="(photo, index) in photos" :key="index">
            <image
              class="photo-preview"
              :src="photo.path"
              mode="aspectFill"
              @tap="previewPhotos(index)"
            />
            <view class="delete-btn" @tap="deletePhoto(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>

          <!-- 添加照片按钮 -->
          <view class="add-photo-btn" @tap="choosePhotos" v-if="photos.length < maxPhotoCount">
            <text class="add-icon">+</text>
            <text class="add-text">添加照片</text>
          </view>
        </view>

        <text class="tip-text">最多可上传9张照片</text>
      </view>

      <!-- 视频上传区域 -->
      <view class="media-upload-area" v-if="publishType === 'video' && showMediaSelector">
        <!-- 已上传视频预览 -->
        <view class="video-container" v-if="video.path">
          <video class="video-preview" :src="video.path" object-fit="cover" controls></video>
          <view class="delete-btn video-delete" @tap="deleteVideo">
            <text class="delete-icon">×</text>
          </view>
        </view>

        <!-- 添加视频按钮 -->
        <view class="add-video-btn" @tap="chooseVideo" v-if="!video.path">
          <image src="/static/images/video-add.png" mode="aspectFit" />
          <text class="add-text">添加视频</text>
        </view>

        <text class="tip-text">视频最长60秒</text>
      </view>

      <!-- 发布按钮区域 -->
      <view class="publish-buttons">
        <button
          class="publish-btn text-btn"
          :class="{ active: publishType === 'text' }"
          :disabled="isPublishing || contentText.trim() === ''"
          @tap="handleTextPublish"
        >
          <image src="/static/images/text.png" mode="aspectFit" />
          <text>文字发布</text>
        </button>

        <button
          class="publish-btn photo-btn"
          :class="{ active: publishType === 'photo' }"
          :disabled="isPublishing"
          @tap="handlePhotoPublish"
        >
          <image src="/static/images/photo.png" mode="aspectFit" />
          <text>照片发布</text>
        </button>

        <button
          class="publish-btn video-btn"
          :class="{ active: publishType === 'video' }"
          :disabled="isPublishing"
          @tap="handleVideoPublish"
        >
          <image src="/static/images/video.png" mode="aspectFit" />
          <text>视频发布</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { sendPhonePost, sendVideoPost, sendTextPost, sendMultiplePhonePost } from '@/api/public'

export default {
  data() {
    return {
      contentText: '',
      publishType: 'text', // 默认为文字发布模式
      photos: [], // 照片数组 [{path: ''}]
      video: { path: '' }, // 视频对象
      isPublishing: false,
      maxPhotoCount: 9, // 最大照片数量
      showMediaSelector: true, // 是否显示媒体选择器
      userId: null, // 用户ID
    }
  },

  // 页面加载时获取用户信息
  onLoad() {
    // 获取用户信息
    this.getUserInfo()
    console.log('页面加载完成，当前用户ID:', this.userId)
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          const userInfoObj = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
          this.userId = userInfoObj.id
          console.log('获取到用户ID:', this.userId)
        } else {
          console.warn('本地存储中未找到用户信息')
        }
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }
    },

    // 处理文字发布按钮点击
    handleTextPublish() {
      this.publishType = 'text'
      this.showMediaSelector = false
      this.publishPost('text')
    },

    // 处理照片发布按钮点击
    handlePhotoPublish() {
      this.publishType = 'photo'
      this.showMediaSelector = true

      if (this.photos.length > 0) {
        // 如果已有照片，直接发布
        this.publishPost('photo')
      } else {
        // 没有照片，弹出选择器
        this.choosePhotos()
      }
    },

    // 处理视频发布按钮点击
    handleVideoPublish() {
      this.publishType = 'video'
      this.showMediaSelector = true

      if (this.video.path) {
        // 如果已有视频，直接发布
        this.publishPost('video')
      } else {
        // 没有视频，弹出选择器
        this.chooseVideo()
      }
    },

    // 选择照片
    choosePhotos() {
      const remainCount = this.maxPhotoCount - this.photos.length
      uni.chooseImage({
        count: remainCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          tempFilePaths.forEach((path) => {
            this.photos.push({
              path: path,
            })
          })
        },
      })
    },

    // 预览照片
    previewPhotos(index) {
      const urls = this.photos.map((photo) => photo.path)
      uni.previewImage({
        urls: urls,
        current: urls[index],
      })
    },

    // 删除照片
    deletePhoto(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这张照片吗？',
        success: (res) => {
          if (res.confirm) {
            this.photos.splice(index, 1)
          }
        },
      })
    },

    // 选择视频
    chooseVideo() {
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back',
        success: (res) => {
          this.video.path = res.tempFilePath
        },
      })
    },

    // 删除视频
    deleteVideo() {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个视频吗？',
        success: (res) => {
          if (res.confirm) {
            this.video.path = ''
          }
        },
      })
    },

    // 发布动态
    async publishPost(type) {
      if (type) {
        this.publishType = type
      }

      // 验证发布内容
      let isValid = false
      let errorMessage = ''

      if (this.publishType === 'text') {
        isValid = this.contentText.trim() !== ''
        errorMessage = '请输入文字内容'
      } else if (this.publishType === 'photo') {
        isValid = this.photos.length > 0
        errorMessage = '请选择至少一张照片'
      } else if (this.publishType === 'video') {
        isValid = this.video.path !== ''
        errorMessage = '请选择一个视频'
      }

      if (!isValid) {
        uni.showToast({
          title: errorMessage,
          icon: 'none',
        })
        return
      }

      // 检查用户ID
      if (!this.userId) {
        try {
          this.getUserInfo()
          if (!this.userId) {
            uni.showToast({
              title: '用户信息获取失败，请重新登录',
              icon: 'none',
            })
            return
          }
        } catch (error) {
          uni.showToast({
            title: '用户信息获取失败，请重新登录',
            icon: 'none',
          })
          return
        }
      }

      this.isPublishing = true
      uni.showLoading({
        title: '发布中...',
      })

      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          throw new Error('请先登录')
        }

        let result

        // 根据发布类型选择不同的API接口
        if (this.publishType === 'text') {
          // 文字发布
          console.log('发送文字动态，用户ID:', this.userId, '内容:', this.contentText)
          result = await sendTextPost(this.userId, this.contentText)
          console.log('文字发布响应结果:', result)
        } else if (this.publishType === 'photo') {
          // 照片发布 - 使用多张照片上传接口
          if (this.photos.length > 0) {
            // 收集所有照片路径
            const photoPaths = this.photos.map((photo) => photo.path)

            // 使用批量上传接口
            result = await sendMultiplePhonePost(this.userId, this.contentText, photoPaths)

            console.log('多张照片上传结果:', result)

            // 检查是否所有照片都上传成功
            const allSuccess =
              Array.isArray(result) &&
              result.every(
                (res) => res && (res.code === 200 || (res.data && res.data.code === 200)),
              )

            if (!allSuccess) {
              throw new Error('部分照片上传失败，请重试')
            }
          } else {
            throw new Error('请选择照片')
          }
        } else if (this.publishType === 'video') {
          // 视频发布
          if (this.video.path) {
            result = await sendVideoPost(this.userId, this.contentText, this.video.path)
          } else {
            throw new Error('请选择视频')
          }
        }

        console.log('发布结果:', result)

        // 检查响应结果
        const isSuccess =
          // 单个响应成功
          (result && result.code === 200) ||
          (result && result.statusCode === 200 && result.data && result.data.code === 200) ||
          // 多个响应全部成功
          (Array.isArray(result) &&
            result.length > 0 &&
            result.every((res) => res && (res.code === 200 || (res.data && res.data.code === 200))))

        if (isSuccess) {
          uni.showToast({
            title: '发布成功',
            icon: 'success',
          })

          // 重置表单
          this.contentText = ''
          this.photos = []
          this.video.path = ''

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          const errorMsg =
            (result && result.data && result.data.message) ||
            (result && result.message) ||
            '发布失败'
          throw new Error(errorMsg)
        }
      } catch (error) {
        console.error('发布失败', error)
        uni.showToast({
          title: error.message || '发布失败，请重试',
          icon: 'none',
        })
      } finally {
        this.isPublishing = false
        uni.hideLoading()
      }
    },
  },
}
</script>

<style lang="scss">
@import '@/styles/variables.scss';

.public-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;

  .header {
    height: 200rpx;
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    border-radius: 0 0 40rpx 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .title {
      color: #ffffff;
      font-size: 36rpx;
      font-weight: bold;
    }
  }

  .content-box {
    margin: -60rpx 30rpx 0;
    background-color: #ffffff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    padding: 30rpx;

    .text-area {
      position: relative;
      margin-bottom: 30rpx;

      .content-textarea {
        width: 100%;
        min-height: 200rpx;
        font-size: 28rpx;
        padding: 20rpx 0;
        line-height: 1.6;
      }

      .text-counter {
        position: absolute;
        bottom: 0;
        right: 0;
        font-size: 24rpx;
        color: #999999;
      }
    }

    .media-upload-area {
      padding: 20rpx 0;
      margin-bottom: 30rpx;

      .photo-grid {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10rpx;

        .photo-item,
        .add-photo-btn {
          width: calc(33.333% - 20rpx);
          height: 200rpx;
          margin: 10rpx;
          border-radius: 12rpx;
          overflow: hidden;
        }

        .photo-item {
          position: relative;

          .photo-preview {
            width: 100%;
            height: 100%;
            border-radius: 12rpx;
          }

          .delete-btn {
            position: absolute;
            top: 10rpx;
            right: 10rpx;
            width: 40rpx;
            height: 40rpx;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            .delete-icon {
              color: #ffffff;
              font-size: 32rpx;
              line-height: 1;
            }
          }
        }

        .add-photo-btn {
          border: 2rpx dashed #cccccc;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background-color: #f9f9f9;

          .add-icon {
            font-size: 48rpx;
            color: #999999;
            line-height: 1;
            margin-bottom: 10rpx;
          }

          .add-text {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }

      .video-container {
        position: relative;
        width: 100%;
        height: 400rpx;
        border-radius: 12rpx;
        overflow: hidden;
        margin-bottom: 20rpx;

        .video-preview {
          width: 100%;
          height: 100%;
          border-radius: 12rpx;
        }

        .video-delete {
          top: 20rpx;
          right: 20rpx;
          width: 60rpx;
          height: 60rpx;
          z-index: 10;

          .delete-icon {
            font-size: 40rpx;
          }
        }
      }

      .add-video-btn {
        width: 100%;
        height: 400rpx;
        border: 2rpx dashed #cccccc;
        border-radius: 12rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #f9f9f9;

        image {
          width: 100rpx;
          height: 100rpx;
          margin-bottom: 20rpx;
        }

        .add-text {
          font-size: 28rpx;
          color: #999999;
        }
      }

      .tip-text {
        display: block;
        font-size: 24rpx;
        color: #999999;
        text-align: center;
        margin-top: 20rpx;
      }
    }

    .publish-buttons {
      display: flex;
      justify-content: space-between;

      .publish-btn {
        flex: 1;
        height: 88rpx;
        margin: 0 10rpx;
        background-color: #f5f5f5;
        color: #666666;
        font-size: 28rpx;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;

        &:first-child {
          margin-left: 0;
        }

        &:last-child {
          margin-right: 0;
        }

        &.active {
          background-color: $theme-color;
          color: #ffffff;
        }

        &[disabled] {
          background-color: #cccccc;
          color: #999999;
          opacity: 0.8;
        }

        image {
          width: 32rpx;
          height: 32rpx;
          margin-right: 10rpx;
        }

        &::after {
          border: none;
        }
      }
    }
  }
}
</style>
